package com.example.demo.leetcode.top100;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _6三数之和
 * @description
 * @date 2023/06/03 22:54
 * <p>
 * ******************************************************
 */
public class _6三数之和 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new LinkedList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            final List<List<Integer>> lists = twoSumTarget(nums, i + 1, 0 - nums[i]);
            for (List<Integer> list : lists) {
                list.add(nums[i]);
                res.add(list);
            }
            // 跳过第一个数字重复的情况，否则会出现重复结果
            while (i < nums.length - 1 && nums[i] == nums[i + 1]) i++;
        }
        return res;
    }

    private List<List<Integer>> twoSumTarget(int[] nums, int start, int target) {
        List<List<Integer>> res = new LinkedList<>();
        // 左右指针
        int lo = start, hi = nums.length - 1;
        while (lo < hi) {
            // 记录索引 lo 和 hi 最初对应的值
            int left = nums[lo], right = nums[hi];
            int sum = nums[lo] + nums[hi];
            if (sum > target) {
                while (lo < hi && nums[hi] == right) hi--;
            } else if (sum < target) {
                while (lo < hi && nums[lo] == left) lo++;
            } else {
                List<Integer> list = new LinkedList<>();
                list.add(nums[lo]);
                list.add(nums[hi]);
                res.add(list);
                // 跳过所有重复的元素
                while (lo < hi && nums[lo] == left) lo++;
                while (lo < hi && nums[hi] == right) hi--;
            }
        }
        return res;
    }

}